package com.xiaoniu.forum.web.interceptor;

import com.xiaoniu.forum.common.utils.IpAdrressUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

//@Component
public class CurrentLimitingInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String realIp = IpAdrressUtil.getIpAdrress(request);
        Integer visitCount = (Integer) redisTemplate.opsForValue().get("sys:currentLimiting:" + realIp);
        if (visitCount > 10&& visitCount != null){
            return false;
        }else if (visitCount == null){
            redisTemplate.opsForValue().set("sys:currentLimiting:"+realIp,1,1L, TimeUnit.SECONDS);
        }
        return false;
    }
}
